<template>
	<el-dialog :title="dialogTitle" :visible.sync="visible" append-to-body width="480px">
		<el-form ref="form" size="medium" :model="listFrom" :rules="listRules" label-width="90px" class="role_form_wrapper">
			<el-form-item label="名单名称" prop="name">
				<el-input v-model="listFrom.name"></el-input>
			</el-form-item>
			<el-form-item label="名单类型" prop="type">
				<el-radio-group v-model="listFrom.type">
					<el-radio label="1">黑名单</el-radio>
					<el-radio label="2">白名单</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="IP地址" prop="ipAddr">
				<sw-ip-input placeholder="请输入IP地址" v-model="listFrom.ipAddr" size="medium" style="width: 200px"></sw-ip-input>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" :loading="btnLoading" @click="handleSubmitForm">{{ addOrEdit ? '新增' : '修改' }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
import { addedBlack, updateBlack } from '@/api/system/tbSysBlack';
export default {
	props: {
		value: {
			type: Boolean,
			default: false
		},
		data: {
			type: Object,
			default: () => {}
		},
		listType: String
	},
	data() {
		return {
			visible: this.value,
			listFrom: {},
			listRules: {
				name: [{ required: true, message: '请输入名单名称', trigger: 'blur' }],
				ipAddr: [{ required: true, message: '请输入IP地址', trigger: 'blur' }]
			},
			btnLoading: false
		};
	},
	computed: {
		addOrEdit() {
			return Object.keys(this.data).length === 0;
		},
		dialogTitle() {
			return `${this.addOrEdit ? '新增' : '修改'}名单`;
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.$nextTick(() => {
				this.$refs['form'].resetFields();
				this.listFrom = this.addOrEdit ? { type: this.listType } : { ...this.data };
			});
		}
	},
	methods: {
		handleSubmitForm() {
			this.$refs['form'].validate(async (valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				await this.submitFormRequest();
				this.btnLoading = false;
			});
		},

		//添加/修改枚举请求
		async submitFormRequest() {
			let params = { ...this.listFrom };
			let requestFun = eval(this.addOrEdit ? addedBlack : updateBlack);
			let result = await requestFun(params).then((res) => res.data);
			if (result.code === '0') {
				this.$emit('refresh');
				this.visible = false;
				this.$showCustomMessage('success', `${this.addOrEdit ? '新增' : '修改'}名单成功`);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.role_form_wrapper {
	width: 100%;
	padding: 10px 6px 0 0;
	box-sizing: border-box;
}
</style>
